﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Common;
using Common.Enums;
using enterprise.Website.Core.Filter;
using FreeSql.Context;
using FreeSql.Model;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace enterprise.Website.Core.ApiControllers
{
    /// <summary>
    /// 外部接口V1
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    [ApiAuthorize]
    public class V1Controller : ControllerBase
    {
        private SqlContext _sqlContext;
        private readonly IWebHostEnvironment _hostingEnvironment;
        private readonly ICache _cache;
        public V1Controller(SqlContext sqlContext, IWebHostEnvironment hostingEnvironment, ICache cache)
        {
            _sqlContext = sqlContext;
            _hostingEnvironment = hostingEnvironment;
            _cache = cache;
        }

        /// <summary>
        /// 提交产品数据
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost("PushProduct")]
        public ApiResult PushProduct([FromBody] List<Product_Info> data)
        {
            var result = new ApiResult { Success = true, Message = "推送成功" };
            if (data != null && data.Count > 0)
            {
                Task.Run(() => 
                {
                    var sqlContext = _sqlContext;
                    var AddDataList = new List<Product_Info>();
                    string saveRoute = AppSetting.UploadRoute;
                    string rootPath = Path.Combine(_hostingEnvironment.WebRootPath, saveRoute);
                    foreach (var m in data)
                    {
                        var hasPro = sqlContext.QueryCount<Product_Info>(k => k.CasNo == m.CasNo) > 0;
                        if (!hasPro)
                        {
                            if (!m.ClassName.IsNullOrWhiteSpace())
                            {
                                var ClassInfo = sqlContext.QueryInfo<ContentClass>(n => n.ClassName == m.ClassName.Trim());
                                if (ClassInfo != null && ClassInfo.ClassType == (int)ClassType.Products)
                                {
                                    m.ClassId = ClassInfo.Id;
                                    m.LanguageId = ClassInfo.LanguageId;
                                }
                                else
                                {
                                    var enLan = sqlContext.QueryInfo<LanguageType>(orderBy: "IsDefault desc");
                                    if (enLan == null)
                                    {
                                        enLan = _sqlContext.QueryInfo<LanguageType>();
                                    }
                                    var TopClassInfo = sqlContext.QueryInfo<ContentClass>(n => n.ClassType == (int)ClassType.Products && n.ParentId == 0 && n.LanguageId == enLan.Id);
                                    sqlContext.Add(new ContentClass
                                    {
                                        ClassType = (int)ClassType.Products,
                                        IsShow = 0,
                                        ClassName = m.ClassName,
                                        ParentId = TopClassInfo.Id,
                                        LanguageId = enLan.Id
                                    });
                                    _cache.Remove($"{SystemConstConfig.ContentClassKey}_{enLan.Id}");
                                }
                            }
                            else
                            {
                                var enLan = sqlContext.QueryInfo<LanguageType>(orderBy: "IsDefault desc");
                                if (enLan != null)
                                {
                                    var TopClassInfo = sqlContext.QueryInfo<ContentClass>(n => n.ClassType == (int)ClassType.Products && n.ParentId == 0 && n.LanguageId == enLan.Id);
                                    if (TopClassInfo != null)
                                    {
                                        m.LanguageId = enLan.Id;
                                        m.ClassId = TopClassInfo.Id;
                                    }
                                    else
                                    {
                                        m.LanguageId = enLan.Id;
                                        m.ClassId = 0;
                                    }
                                }
                            }
                            var Id = sqlContext.Add(m);
                            foreach (var img in m.PicUrl)
                            {
                                var fileName = Guid.NewGuid().ToString() + Path.GetExtension(img);
                                var isSuccess = HttpHelp.HttpDownLoadFile(img, rootPath, fileName);
                                if (isSuccess > 0)
                                {
                                    sqlContext.Add<Product_Img>(new Product_Img
                                    {
                                        ProId = Id.ObjToInt(),
                                        Img = Path.Combine("/" + saveRoute, fileName),
                                        IsTitle = 0
                                    });
                                }
                            }
                        }
                    }
                }).ContinueWith(t=> RemoveProductCache());
            }
            return result;
        }


        /// <summary>
        /// 删除产品缓存
        /// </summary>
        private void RemoveProductCache()
        {
            var Lantypes = _sqlContext.QueryList<LanguageType>();
            if (Lantypes != null && Lantypes.Count > 0)
            {
                foreach (var item in Lantypes)
                {
                    _cache.Remove($"{SystemConstConfig.Products}_{item.Id}");
                }
            }
        }
    }
}
